#include <types.h>
#include <HTTP.h>
#include <Exception.h>

HTTP::HTTP(Address *addr)
{
    this->addr=addr;
    status=HTTP_CONNECTION_CLOSED;
}


HTTP::~HTTP()
{
    if (status==HTTP_CONNECTION_ESTABLISHED)
	delete this->stcp;
}


void HTTP::connect()
{
    stcp=new SocketTCP(*this->addr);
    
    stcp->establish();
    status=HTTP_CONNECTION_ESTABLISHED;
}


void HTTP::urlencode(char *orig, char *dest, int bufsize)
{
    char c;
    int j=0;
    
    for (int i=0; i<MIN(bufsize, strlen(orig)); i++)
    {
	c=orig[i];
	
	if (c>32 && c<128)
	{
	    dest[j]=c;
	    j++;
	}
	else
	{
	    sprintf(&dest[j], "%%%2x", c);
	    j+=3;
	}
    }
}


int HTTP::sendMessage(HTTPMessage *msg)
{
    char buf[4096];
    
    if (msg==NULL)
	return -1;

    memset(buf, 0, sizeof(buf));
    
    msg->toString(buf, sizeof(buf));
    
    stcp->write(buf, strlen(buf));
    
    return 0;
}


int HTTP::recvMessage(HTTPMessageResponse *msg)
{
    char buf[4096];
    int llegits=0;
    int total=0;
    memset(buf, 0, sizeof(buf));
    
    if (msg==NULL)
	return -1;

    
    do
    {
	llegits=stcp->read(&buf[total], sizeof(buf));
	total+=llegits;
	
    } while (llegits!=0);

    msg->setContent(buf);
   
    return 0;
}
